# %%
import os
import sys
import time
from playwright.sync_api import sync_playwright
import re
import beauty

os.chdir(os.path.dirname(__file__))

def pull_passage(test=False, index=0):
    with sync_playwright() as p:
        pwd = os.path.abspath(os.path.dirname(__file__))
        pwd = os.path.join(pwd, 'apnews')
        if sys.platform == 'win32':
            pwd = 'D:/eglwa/home/apnews'
            browser = p.chromium.launch(headless=not test).new_context()
        elif sys.platform == 'linux':
            browser = p.chromium.launch(headless=not test).new_context()
        elif sys.platform == 'darwin':
            browser = p.webkit.launch(headless=not test).new_context()
        else:
            raise Exception('Not supported platform')
        page = browser.new_page()

        if not os.path.exists(pwd):
            os.mkdir(pwd)
        top_news_url, img_src = beauty.get_top_news_url(index)
        html_file = 'test.html'
        html_file = os.path.join(pwd, html_file)

        title = beauty.get_top_news_article(top_news_url, html_file, img_src)
        today = time.strftime('%m-%d', time.localtime())
        if test:
            print('pull passage done:', title)
        title = re.sub(r'[^\w ]', '', title)
        if sys.platform == 'win32':
            pdf_file = os.path.join(pwd, f'{today} {title}.pdf')
        else:
            pdf_file = os.path.join(pwd, f'{today}.pdf')
        page.goto(f'file://{html_file}')
        page.pdf(path=pdf_file, margin={
                 "top": "1cm", "bottom": "1cm", "left": "1cm", "right": "1cm"})
        return pdf_file


# %%
if __name__ == '__main__':
    index = 0
    if len(sys.argv) > 1:
        index = int(sys.argv[1])
    pdf_file = pull_passage(False, index=index)

    if sys.platform != 'win32':
        pass
    else:
        os.system(f'"{pdf_file}"')
